﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MassTransit;
using MassTransit.ExtensionsDependencyInjectionIntegration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Order.API.Data;
using Order.API.Data.AggregatesModel;
using Order.API.Services.Commands;
using Order.API.Services.Jobs;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;

namespace Order.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<OrderContext>();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddScoped<IJob, OrderCreatedJob>();
            services.AddMassTransit(cfg =>
            {
                cfg.AddConsumer<CreateOrderCmdHandler>();
            });
            services.AddScoped<CreateOrderCmdHandler>();
            BusControl = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host(new Uri("rabbitmq://140.143.88.100/"), hostCfg =>
                {
                    hostCfg.Username("guest");
                    hostCfg.Password("guest");
                });
                cfg.ReceiveEndpoint(host, "OrderQueue", endpointCfg =>
                {
                    //endpointCfg.Consumer<OrderCreatedEventHandler>();
                    //endpointCfg.Consumer<CreateOrderCmdHandler>();
                    endpointCfg.LoadFrom(services.BuildServiceProvider());
                });
            });
            SendEndpoint = BusControl.GetSendEndpoint(new Uri("rabbitmq://140.143.88.100/OrderQueue")).Result;
        }
        public static IBusControl BusControl { get; private set; }
        public static ISendEndpoint SendEndpoint { get; private set; }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime applicationLifetime)
        {
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler().Result;
            IJobDetail jobDetail = new JobDetailImpl(nameof(OrderCreatedJob), typeof(OrderCreatedJob));
            IMutableTrigger trigger = CalendarIntervalScheduleBuilder.Create()
                .WithInterval(3, IntervalUnit.Second)
                .Build();
            trigger.Key = new TriggerKey("key", "group");
            scheduler.ScheduleJob(jobDetail, trigger).Wait();


            applicationLifetime.ApplicationStarted.Register(() =>
            {
                BusControl.Start();
                scheduler.Start().Wait();
            });
            applicationLifetime.ApplicationStopped.Register(() =>
            {
                BusControl.Stop();
                scheduler.Shutdown().Wait();
            });
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

